package com.itheima.utils;

import io.jsonwebtoken.*;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.util.Date;

public class JwtUtils2 {
    // 自定义秘钥
    private static String JWT_SECERT = "XXXXXX";


    /**
     * 签发JWT
     *
     * @param userId   用户ID
     * @param userName 用户名
     * @return
     */
    public static String createJWT(Double userId, String userName) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(String.valueOf(userId))
                .setSubject(userName)   // 主题
                .setIssuer("user")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        // 设置1小时超时
        long expMillis = nowMillis + 1 * 60 * 60 * 1000;
        Date expDate = new Date(expMillis);
        builder.setExpiration(expDate); // 过期时间

        return builder.compact();
    }

    /**
     * 验证JWT
     *
     * @param jwtStr
     * @return
     */
    public static CheckResult validateJWT(String jwtStr) {
        CheckResult checkResult = new CheckResult();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            checkResult.setSuccess(true);
            checkResult.setClaims(claims);
        } catch (ExpiredJwtException e) {
            System.out.println("jwt超时异常！");
            checkResult.setSuccess(false);
        } catch (SignatureException e) {
            System.out.println("jwt验证异常！");
            checkResult.setSuccess(false);
        } catch (Exception e) {
            System.out.println("jwt未知错误！");
            checkResult.setSuccess(false);
        }
        return checkResult;
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECERT);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析JWT字符串
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }


    public static void main(String[] args) throws Exception {
        String s = encodeTelephone("15632621046");
        System.out.println(s);
        String string = decodeTelephone(s);
        System.out.println(string);
    }

    //加密手机号
    public static String encodeTelephone(String telephone) {
        double d = new BigDecimal(telephone).doubleValue();
        String jwt = createJWT(d, "");
        System.out.println(jwt);
        return jwt;
    }

    //解密手机号
    public static String decodeTelephone(String encodeTel) throws Exception {
        String id = validateJWT(encodeTel).getClaims().getId();
        String telephone = id.substring(0, 1) + id.substring(2, 12);
        System.out.println(telephone);
        return telephone;
    }
}
